<template>
  <div class="tabbar">
    <van-tabbar
      v-model="active"
      @change="handleChange"
    >
      <van-tabbar-item
        v-for="item in tabbarIcon"
        :key="item.text"
        replace
        :to="item.path"
      >
        <span>{{ item.text }}</span>
        <template #icon="props">
          <i
            class="iconfont"
            :class="props.active ? item.icon : item.icon"
          ></i>
        </template>
      </van-tabbar-item>
      <van-tabbar-item
        replace
        to="/my"
        :dot="showMsgDot"
        :badge="alarmMsgNum"
      >
        <span>我的</span>
        <template #icon="props">
          <i
            class="iconfont"
            :class="props.active ? 'iconwode' : 'iconwode'"
          ></i>
        </template>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import { Tabbar, TabbarItem } from 'vant';
export default {
  name: 'Tabbar',
  components: {
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem
  },
  computed: {
    // 显示消息红点
    showMsgDot() {
      return this.$store.state.messageNum.unread > 0 && this.$store.state.messageNum.alarm === 0;
    },
    // 报警消息条数
    alarmMsgNum() {
      return this.$store.state.messageNum.alarm;
    }
  },
  data() {
    return {
      active: this.$store.state.tabbarActive,
      tabbarIcon: []
    };
  },
  created() {
    if (this.$store.state.apps.length) {
      let apps = [
        {
          text: '设备中心',
          icon: 'iconshebeiguanli',
          path: '/deviceCenter',
          requestName: 'iot_device'
        },
        {
          text: '维保中心',
          icon: 'iconweixiubaoyang-01',
          path: '/maintenanceCenter',
          requestName: 'iot_maintenance'
        },
        {
          text: '项目中心',
          icon: 'iconxiangmu',
          path: '/projectCenter',
          requestName: 'iot_project'
        }
      ];

      apps.map(item => {
        for (let i = 0; i < this.$store.state.apps.length; i++) {
          let subItem = this.$store.state.apps[i];
          if (subItem.request_name === item.requestName) {
            this.tabbarIcon.unshift(item);
            break;
          }
        }
      });

      if (this.$store.state.isRefreshAuth) {
        this.handleChange(0);
        setTimeout(() => {
          this.$router.replace(this.tabbarIcon[0].path);
          this.$store.commit('resetIsRefreshAuth');
        }, 300);
      }
    } else {
      this.$router.replace('/my');
    }
  },
  methods: {
    // 切换tabbar
    handleChange(index) {
      this.$store.commit('resetTabbarActive', index);
    }
  }
};
</script>

<style lang="scss" scoped>
.tabbar {
  flex-shrink: 0;
  width: 100%;
  height: 1.333333rem;

  ::v-deep .van-tabbar {
    position: unset;
  }
}
</style>